<?php
class Page extends Podcast {
	private $dir;
	private $controller;
	private $header = "";
	private $content = "";

	private static $template = "app/home.htpl";

	function __construct(PostController $controller) {
		// separate paramters
		$params = explode('/', preg_replace("#".ROOT_DIR."#", "", $_SERVER["REQUEST_URI"], 1));
		@$this->dir = $params[1];
		@self::$podcast  = $params[2];
		(isset($params[3])) ? self::$episode = $params[3] : self::$episode = "";

		$this->header = "Podcastproject/";
		foreach ($params as $params) {
			if($params != "") {
				$this->header .= " ".ucfirst($params)."/";
			}
		}

		$this->controller = $controller;
	}

	public function render() {
		// show a feed or the whole list?
		switch ($this->dir) {
			case "directory.opml":
				Logger::add("directory.opml");

				$dir = new OPML();
				$dir->generateOutput();
				break;

			case "feed":
				Logger::add();

				$builder = new Builder();
				$builder->generateOutput();
				break;

			case "logo":
				$logo = new Logo();
				$logo->generateOutput();
				break;

			case "update":
				Logger::add("update");

				$updater = new Updater();
				$updater->execute();
				break;

			default:
				$this->generateContent();
				echo $this->replaceTags();
		}
	}

	private function generateContent() {
		switch ($this->dir) {
			case "":
				$this->addFeedList();
				break;

			case "episodes":
				$ep = new Episodes();
				$this->addContent($ep->getContent());
				break;

			case "flattr":
				$this->addContent("<h2>Flattr the episodes you listened to</h2>");

				$flattr = new Flattr(self::$podcast);
				$this->addContent($flattr->getContent());
				break;

			case "log":
				$this->addContent("<h2>Logfile</h2>");
				$this->addContent("<pre>".file_get_contents(self::$logfile)."</pre>");
				break;

			case "logo":


			case "torrent":
				$this->addContent("<h2>Torrent Feed</h2>");
				$this->addContent("You can use this feed to subscribe with your torrent client.<br>");
				$this->addContent("Every time this feed is called your client will be provided with all torrents from 5 different podcasts.<br><br>");

				$torrentLink = ROOT."feed/torrent/";
				$this->addContent("<a href=\"$torrentLink\">$torrentLink</a>");
				break;

			default:
				$this->addContent("<h2>404 Not Found - That's an error</h2>");
				$this->addContent('<img src="'.ROOT.'app/images/404.jpg" alt="404 Not Found">');
				$this->addContent('<div class="imageTitle">by <a href="http://www.flickr.com/people/mydnight296/">Vannessa</a></div>');
		}
	}

	private function replaceTags() {
		$output = file_get_contents(self::$template);

		// replace dir tags
		$output = preg_replace("#({%dir%})#", ROOT, $output);

		// replace content tag
		$output = preg_replace("#({%content%})#", $this->content, $output);

		// replace current dir/menu
		($this->dir == "episodes") ? $dir = "" : $dir = $this->dir;
		$output = preg_replace("#({%menu $dir%})#", "active", $output);

		// replace logo/header
		$output = preg_replace("#({%logo%})#", "&lt; ".$this->header." &gt;", $output);

		// replace the input values
		$postData = $this->controller->getPostData();
		$output = preg_replace("#({%input feed%})#", $postData["feed"], $output);
		$output = preg_replace("#({%input torrentfeed%})#", $postData["torrentfeed"], $output);
		$output = preg_replace("#({%input name%})#", $postData["name"], $output);
		$output = preg_replace("#({%input tag%})#", $postData["tag"], $output);
		$output = preg_replace("#({%input newPodcast%})#", $postData["newPodcast"], $output);

		// messages from postcontroller
		$postOutput = $this->controller->getOutput();
		$output = preg_replace("#({%controller success%})#", @$postOutput["success"], $output);
		$output = preg_replace("#({%controller error%})#", @$postOutput["error"], $output);

		// replace all unused tags
		$output = preg_replace("#({%.*%})#Us", "", $output);

		return $output;
	}

	private function addFeedList() {
		$query = "SELECT tag, name, feed, torrentfeed FROM  `pp_podcasts` ORDER by name;";
		$res = self::$db->query($query);

		if(!mysql_num_rows($res)) {
			$this->addContent('<h2>Currently no podcast feeds available.</h2>Please add some of your podcasts with the form below.');
		} else {
			$this->addContent('<h2 id="nbOfFeeds">There are '.mysql_num_rows($res).' podcast feeds available:</h2>');
			$this->addContent('<input autocomplete="off" value="" id="search" type="text" onkeyup="filterArticles()" onkeypress="{if (event.keyCode==13)goToArticle()}" class="footerInputAreaAutomatic" tabindex="1" /> <a style="cursor: pointer;" onclick="clearSearch();">∅</a> <br><br>');
			$this->addContent('<div style="text-align: right;"><a href="'.ROOT.'directory.opml">OPML</a></div>');

			$i = 0;
			while ($info = mysql_fetch_assoc($res)) {
				($info["feed"] != $info["torrentfeed"]) ? $noTorrentFeed = "" : $noTorrentFeed = ' (<span style="color: red;"> ! </span>)';
				($this->canUserDelete()) ? $deleteLink = "(delete)" : $deleteLink = "";

				$this->addContent('
								<div id="article_'.$i.'">
								<article class="item" id="'.$info["tag"].'">
								<div>
									<img src="'.ROOT.'logo/'.$info["tag"].'" class="pclogo" alt="Podcastcover"/>
									<div class="right">
										<h3 class="title">'.$info["tag"].'</h3><br>
										<p class="published delete" onclick="deletePodcast(\''.$info["tag"].'\')">'.$deleteLink.'</p>
									</div>
									<div>
										<h3 class="title"><a href="'.ROOT.'episodes/'.$info["tag"].'">'.$info["name"].'</a>'.$noTorrentFeed.'</h3>
									</div>
								</div><br>
								<a href="'.ROOT.'feed/'.$info["tag"].'">'.ROOT.' feed/ <b>'.$info["tag"].'</b></a>
								<br><br>
								</article><br>
								</div>
								<script>pushToArticles(\''.addslashes($info["name"]).'\', \''.$info["tag"].'\');</script>');
				$i++;
			}
		}

		// create hidden form to delete podcasts
		$this->addContent('<form id="delPodcast" method="post" action="'.ROOT.'"><input id="tag" name="delPodcast" type="hidden" /></form>');
	}

	private function addContent($content) {
		$this->content .= "$content\r\n";
	}

	private function canUserDelete() {
		$ip = $_SERVER["REMOTE_ADDR"];
		$pattern = "/\.*\..*\..*\..*/";

		return (boolean) !preg_match($pattern, $ip);
	}
}

?>
